﻿using UnityEngine.UIElements;

namespace winS.UnityEditor.UIElement
{
    /// <summary>
    /// 可隐藏的容器(垂直方向)
    /// </summary>
    public class HideableContainer : VisualElement
    {
        public static readonly float defaultAnimationDuration = 0.2f;

        public bool showed { get; private set; } = true;

        private float lastHeight = -1f;

        internal HideableContainer()
        {
            style.overflow = Overflow.Hidden;
            style.SetTransition("height", defaultAnimationDuration);
            RegisterCallback<TransitionEndEvent>(OnTransitionEndCallback);
            RegisterCallback<GeometryChangedEvent>(GeometryChangedCallback);
        }

        /// <summary>
        /// 显示
        /// </summary>
        public void Show()
        {
            if (showed) return;
            showed = true;
            if (panel == null) return;
            if (lastHeight < 0f)
            {
                lastHeight = layout.height;
                return;
            }
            style.height = lastHeight;
        }
        /// <summary>
        /// 隐藏
        /// </summary>
        public void Hide()
        {
            if (!showed) return;
            showed = false;
            if (panel == null) return;
            style.height = lastHeight = layout.height;
            style.height = 0f;
        }

        private void GeometryChangedCallback(GeometryChangedEvent geometryChangedEvent)
        {
            if (!showed && lastHeight < 0f)
            {
                lastHeight = geometryChangedEvent.newRect.height;
                style.height = 0f;
            }
        }
        private void OnTransitionEndCallback(TransitionEndEvent transitionEndEvent)
        {
            if (showed) style.height = new StyleLength(StyleKeyword.Auto);
        }
    }
}
